package sxe.core.cs511.team2_2;

import java.awt.image.BufferedImage;
import java.util.Calendar;
import snobject.*;
import step.EvaluationFailure;
import step.FunctionWrapper;
import step.exceptions.ResourceUnavailableException;

/** OVERVIEW:  A class that defines the opcode blobcount.  This opcode will take an snImage as an argument
 *  and return an snInteger representing the number of blobs detected in the image.
 *  This class is a procedural abstraction.  The abstraction function is AF(c) = {a blobDetector object}.
 *  The representation invariant is that the blobDetector object must be non-null.
 * @author lisap
 *
 */

public class blobcount extends FunctionWrapper {
	private BlobDetector blobDetector = null;
	private Calendar cal = null;
	
	/** Constructor */
	public blobcount(){
		blobDetector = new BlobDetector(1, false);
		
	}

	/** EFFECTS:  This method takes an snImage as an argument and returns the number of blobs in it.
	 *  REQUIRES:  The first argument to be non-null.
	 * @return an snPiar containing the current time, in milliseconds since Jan 1, 1970,
	 * and the number of blobs in the image.
	 * @throws EvaluationFailure
	 */
	public snObject Call(snObjectArgList argv) throws EvaluationFailure,
			ClassCastException, ArrayIndexOutOfBoundsException,
			ResourceUnavailableException {
		
		snImage sni = argv.popImage();
		
		/* do not directly manipulate the original image, instead work with a copy */
		BufferedImage buffImg = sni.getImageCopy(); 
		BlobBag bag = blobDetector.detectBlobs(buffImg);
		int count = 0;
		if (bag != null)
			count = bag.size();
		
		cal = Calendar.getInstance();
		double thistime = (double)cal.getTimeInMillis();
		return new snPair(new snDouble(thistime), new snInteger(count));
	}

}
